﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using LJLNet.Thread;
using LJLCommon.Helper;
using LJLCommon.Package;

namespace LJLNet.SocketTCPPeer
{
    public abstract class BasePeer
    {
        public Socket mSocket { get; set; }

        public BasePeer(Socket socket)
        {
            mSocket = socket;
            //启动socket
            InitSocket();
        }

        public abstract void OnDisconnect();
        public abstract void OnOperationRequest(Dictionary<byte, object> parameters);        

        protected void InitSocket()
        {
            //开启线程
            BaseThread thread = new ReceiveThread(this);
            thread.Start();
        }

        public void OnOperationResponse(Dictionary<byte, object> parameters)
        {
            //向客户端发送消息
            //序列化
            string message = DictToPackageHelper.Serializa(parameters);

            Package package = new Package() { type = PackageType.Response, parameters = message };
            string packageMessage = XMLHelper.Serialze<Package>(package);

            //字节转化
            var date = ASCIIEncoding.UTF8.GetBytes(packageMessage);
            mSocket.Send(date);
        }

        public void OnOperationEvent(Dictionary<byte, object> dict)
        {
            //向客户端发送消息
            //序列化
            string message = DictToPackageHelper.Serializa(dict);

            Package package = new Package() { type = PackageType.Event, parameters = message };
            message = XMLHelper.Serialze<Package>(package);

            //字节转化
            var date = ASCIIEncoding.UTF8.GetBytes(message);
            mSocket.Send(date);
        }
    }
}
